package com.henry.server;

/**
 * 模拟数据库
 */

import com.henry.model.Grade;
import com.henry.model.Question;
import com.henry.model.User;

import java.io.*;
import java.util.ArrayList;
import java.util.List;


public class Data {
    public static List<User> users = new ArrayList<>();
    public static List<Question> questions = new ArrayList<>();
    public static List<Grade> grades = new ArrayList<>();

    public static List<Question> getQuestions() {
        return questions;
    }

    //程序开始运行时从文本文件中读取信息到集合中
    public static void initData() throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("e:/users.txt"));
        users = (List<User>) ois.readObject();
        ois.close();
    }
    public static void questionInput(String str) throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(str));
        questions.addAll((List<Question>)ois.readObject());
        ois.close();
    }
    //将集合中数据写入文本文件
    public static void closeData() throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("e:/users.txt"));
        oos.writeObject(users);
        oos.close();
    }
    public static void outputGrades(String str) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter(str));
        for (Grade grade : grades) {
            bw.write(grade.getCla() + " " + grade.getUsername() + " " + grade.getName() + " " + grade.getGrade());
            bw.newLine();
        }
        bw.close();
    }

    public static void putGrade(String userName, String name, String cla, int grade) {
        grades.add(new Grade(userName, name, cla, grade));
    }
}
